<template>
	<view class="content">
		<view class="row b-b">
			<text class="tit zy-required">收货人</text>
			<input class="input" type="text" v-model="addressData.realName" placeholder="收货人姓名" placeholder-class="placeholder" />
		</view>
		<view class="row b-b">
			<text class="tit zy-required">手机号</text>
			<input class="input" type="number" v-model="addressData.phone" placeholder="收货人手机号码" placeholder-class="placeholder" />
		</view>
		<view class="row b-b">
			<text class="tit zy-required">所在区域</text>
			<text @click="showMulLinkageThreePicker" class="input">
				{{addressData.addressAlias}}
			</text>
			<mpvue-city-picker :themeColor="themeColor" ref="mpvueCityPicker" :pickerValueDefault="defaultAreaValue"
			 @onCancel="onCancel" @onConfirm="onConfirm"></mpvue-city-picker>
		</view>
		<view class="row b-b"> 
			<text class="tit zy-required">详细地址</text>
			<input class="input" type="text" v-model="addressData.address" placeholder="如街道、门牌号、小区、楼栋号、单元室" placeholder-class="placeholder" />
		</view>
		
		<view class="row default-row">
			<text class="tit">设为默认</text>
			<switch :checked="addressData.isDefault == 1" color="#fa436a" @change="switchChange" />
		</view>
		
		<view class="row default-row" @click="deleteAddress" v-if="type === 'edit'">
			<text class="tit" style="color: red;">删除收货地址</text>
		</view>
		<button class="add-btn" @click="confirm" :disabled="submitAddress">提交</button>
	</view>
</template>

<script>
	import zyworkIcon from '@/components/zywork-icon/zywork-icon.vue'
	import { doPostJson, doGet, showInfoToast,USER_PHONE, isPhone } from '@/common/util.js'
	import * as ResponseStatus from '@/common/response-status.js'
	import mpvueCityPicker from '@/components/mpvue-citypicker/mpvueCityPicker.vue'
	
	export default {
		components: {
			zyworkIcon,
			mpvueCityPicker
		},
		data() {
			return {
				type: 'add',
				addressData: {
					realName: '',
					phone: '',
					addressAlias: '请选择所在区域', //用来存储江西省-赣州市-章贡区
					address: '', // 详细地址
					area: null, // 用来存储[0,0,0]类似的数据
					isDefault: 0
				},
				detailAddress: true,
				defaultAreaValue: [0, 0, 0],
				themeColor: '#fa436a',
				urls: {
					saveUrl: '/shipping-address/user/save',
					updateUrl: '/shipping-address/user/update',
					deleteUrl: '/shipping-address/user/remove/',
				},
				submitAddress: false
			}
		},
		onLoad(option){
			let title = '新增收货地址';
			this.detailAddress = true
			if(option.type==='edit'){
				title = '编辑收货地址'
				this.detailAddress = false
				this.addressData = JSON.parse(option.data)
				this.defaultAreaValue = JSON.parse(this.addressData.area)
			} else if (option.type === 'add') {
				this.addressData.isDefault = option.isDefault
				const userPhone = uni.getStorageSync(USER_PHONE);
				if (userPhone) {
					this.addressData.phone = userPhone;
				}
			}
			
			this.type = option.type
			uni.setNavigationBarTitle({
				title
			})
		},
		onBackPress() {
		  if (this.$refs.mpvueCityPicker.showPicker) {
		  	this.$refs.mpvueCityPicker.pickerCancel();
		    return true;
		  }
		},
		onUnload() {
			if (this.$refs.mpvueCityPicker.showPicker) {
				this.$refs.mpvueCityPicker.pickerCancel()
			}
		},
		methods: {
			switchChange(e){
				console.log(e.detail)
				var val = e.detail;
				this.addressData.isDefault = val.value ? 1 : 0;
				console.log(this.addressData.isDefault)
			},
			showMulLinkageThreePicker() {
				this.$refs.mpvueCityPicker.show()
			},
			onCancel(e) {},
			onConfirm(e) {
				// JSON.stringify(e)
				// {"label":"北京市-市辖区-东城区","value":[0,0,0],"cityCode":"110101"}
				this.addressData.addressAlias = e.label.replace(/-/g, '')
				this.addressData.area = JSON.stringify(e.value)
				let addressArr = e.label.split('-')
				this.addressData.province = addressArr[0]
				this.addressData.city = addressArr[1]
				this.addressData.district = addressArr[2]
			},
			//地图选择地址
			chooseLocation(){
				let myThis = this
				uni.authorize({
					scope: 'scope.userLocation',
					success() {
						uni.chooseLocation({
							success: (data)=> {
								if (data.name) {
									myThis.addressData.addressAlias = data.name;
									myThis.addressData.address = data.address;
								}
							}
						})
					},
					fail() {
						showInfoToast('必须授权才能获取位置信息')
					}
				})
			},
			/**
			 * 删除收货地址
			 */
			deleteAddress() {
				uni.showModal({
					content: '您确定要删除收货地址吗？',
					success: (res) => {
						if (res.confirm) {
							doGet(this.urls.deleteUrl + this.addressData.id, {}, {}, true).then(response => {
								let [error, res] = response;
								if (res.data.code === ResponseStatus.OK) {
									this.$api.prePage().refreshList();
									uni.navigateBack()
								} else {
									showInfoToast(res.data.message);
								}
							}).catch(err => {
								console.log(err);
							})
						}
					}
				})
			},
			//提交
			confirm(){
				let data = this.addressData;
				if(!data.realName){
					showInfoToast('请填写收货人姓名');
					return;
				}
				if(!isPhone(data.phone)){
					showInfoToast('请填写正确的手机号码');
					return;
				}
				if (!data.addressAlias) {
					showInfoToast('请选择所在区域')
					return
				}
				if(!data.address){
					showInfoToast('请填写详细地址');
					return;
				}
				if(!data.area){
					showInfoToast('请填写门牌号信息');
					return;
				}
				let url = this.urls.saveUrl;
				if (this.type === 'edit') {
					url = this.urls.updateUrl;
				}
				this.submitAddress = true
				doPostJson(url, data, {}, true).then(response => {
					let [error, res] = response;
					if (res.data.code === ResponseStatus.OK) {
						//this.$api.prePage()获取上一页实例，可直接调用上页所有数据和方法，在App.vue定义
						this.$api.prePage().refreshList()
						uni.navigateBack()
						this.submitAddress = false
					} else {
						showInfoToast(res.data.message)
						this.submitAddress = false
					}
				}).catch(err => {
					console.log(err)
				})
				
			}
		}
	}
</script>

<style lang="scss">
	@import '@/common/zywork-main.scss';
	page{
		background: $page-color-base;
		padding-top: 16upx;
	}

	.row{
		display: flex;
		align-items: center;
		position: relative;
		padding:0 30upx;
		height: 110upx;
		background: #fff;
		
		.tit{
			flex-shrink: 0;
			width: 140upx;
			font-size: 30upx;
			color: $font-color-dark;
		}
		.input{
			flex: 1;
			font-size: 30upx;
			color: $font-color-light;
		}
		.icon-shouhuodizhi{
			font-size: 36upx;
			color: $font-color-light;
		}
	}
	.default-row{
		margin-top: 16upx;
		.tit{
			flex: 1;
		}
		switch{
			transform: translateX(16upx) scale(.9);
		}
	}
	.add-btn{
		display: flex;
		align-items: center;
		justify-content: center;
		width: 690upx;
		height: 80upx;
		margin: 60upx auto;
		font-size: $font-lg;
		color: #fff;
		background-color: $base-color;
		border-radius: 10upx;
		box-shadow: 1px 2px 5px rgba(219, 63, 96, 0.4);
	}
</style>
